package ldh.im.fxgui.controller.sub;

import com.jfoenix.controls.JFXDialog;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import ldh.im.fxbase.cell.ObjectListCell;
import ldh.im.fxbase.dao.ImMessageSendDao;
import ldh.im.fxbase.data.pojo.ImMessage;
import ldh.im.fxbase.data.pojo.ImMessageSend;
import ldh.im.fxbase.data.pojo.ImUser;
import ldh.im.fxbase.data.pojo.status.ImMessageActionStatus;
import ldh.im.fxbase.util.*;
import ldh.im.fxgui.util.UiUtil;
import ldh.im.fxgui.util.UserHeadImageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 聊天-》会话-》群消息-》未读
 * 展示消息已读情况：哪些用户已读，哪些用户未读
 */
public class MessageReadInfoController implements Initializable {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageReadInfoController.class);

    @FXML private ListView<ImMessageSend> readUserListView;
    @FXML private ListView<ImMessageSend> noReadUserListView;
    @FXML private ToggleButton selectReadBtn;
    @FXML private ToggleButton selectNoReadBtn;
    @FXML private TextField searchTextField;
    @FXML private Label closeLabel;

    private ObservableList<ImMessageSend> readList = FXCollections.observableArrayList();
    private FilteredList<ImMessageSend> readFilterList = new FilteredList<>(readList, s -> true);
    private SortedList<ImMessageSend> readSortedList = new SortedList<>(readFilterList, this::messageSendComparator);

    private ObservableList<ImMessageSend> noReadList = FXCollections.observableArrayList();
    private FilteredList<ImMessageSend> noReadFilterList = new FilteredList<>(noReadList, s -> true);
    private SortedList<ImMessageSend> noReadSortedList = new SortedList<>(noReadFilterList, this::messageSendComparator);

    private ImMessageSendDao messageSendDao = BeanFactory.getInstance().getBean(ImMessageSendDao.class);

    private ToggleGroup selectGroup = new ToggleGroup();
    private JFXDialog dialog;
    private ImMessage imMessage;

    public void setDialog(JFXDialog dialog) {
        this.dialog = dialog;
        if (dialog == null) {
            closeLabel.setVisible(false);
        }
    }

    public void setImMessage(ImMessage imMessage) {
        this.imMessage = imMessage;

        ThreadPoolUtil.submit(()->{
            try {
                List<ImMessageSend> messageSendSet = messageSendDao.getByMessageId(imMessage.getId());
                List<ImMessageSend> readMessageSendList = new ArrayList<>();
                List<ImMessageSend> noReadMessageSendList = new ArrayList<>();
                for (ImMessageSend messageSend : messageSendSet) {
                    if (messageSend.getActionStatus() == ImMessageActionStatus.none) {
                        noReadMessageSendList.add(messageSend);
                    } else if (messageSend.getActionStatus() == ImMessageActionStatus.read) {
                        readMessageSendList.add(messageSend);
                    } else if (messageSend.getActionStatus() == ImMessageActionStatus.readed) {
                        readMessageSendList.add(messageSend);
                    } else if (messageSend.getActionStatus() == ImMessageActionStatus.readed) {
                        readMessageSendList.add(messageSend);
                    }
                }
                if (readMessageSendList.size() > 0 || noReadMessageSendList.size() > 0) {
                    FxThreadUtil.runLater(()->{
                        if (readMessageSendList.size() > 0) {
                            readList.setAll(readMessageSendList);
                        }
                        if (noReadMessageSendList.size() > 0) {
                            noReadList.setAll(noReadMessageSendList);
                        }
                    });
                }
            } catch (Exception e) {
                LOGGER.error("加载已读消息失败", e);
            }
        });
    }

    @FXML
    public void searchAct(ActionEvent actionEvent) {
        search();
    }

    @FXML
    public void close() {
        if (dialog != null) {
            dialog.close();
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        selectReadBtn.setToggleGroup(selectGroup);
        selectNoReadBtn.setToggleGroup(selectGroup);

        readUserListView.setItems(readSortedList);
        noReadUserListView.setItems(noReadSortedList);

        readUserListView.setCellFactory(new ObjectListCell<>(this::createListCell));
        noReadUserListView.setCellFactory(new ObjectListCell<>(this::createListCell));

        searchTextField.textProperty().addListener((InvalidationListener) l->{
            search();
        });

        selectReadBtn.setSelected(true);
    }

    @FXML
    public void selectReadAct() {
        readUserListView.setVisible(true);
        noReadUserListView.setVisible(false);
    }

    @FXML
    public void selectNoReadAct() {
        readUserListView.setVisible(false);
        noReadUserListView.setVisible(true);
    }

    private Node createListCell(ImMessageSend messageSend) {
        Label label = new Label();
        ImUser imUser = ImCacheFactory.getInstance().getUser(messageSend.getUserId());
        label.setText(imUser.getUserName());

        ImageView headImageView = new ImageView(UserHeadImageUtil.getHeadImage(imUser.getHeadImg()));
        headImageView.setFitHeight(50);
        headImageView.setFitWidth(50);

        label.setGraphic(headImageView);

        label.setContentDisplay(ContentDisplay.LEFT);
        label.setContextMenu(createContextMenu(imUser));
        return label;
    }

    private void search() {
        String filter = searchTextField.getText().trim();
        if(filter == null || filter.length() == 0) {
            readFilterList.setPredicate(s -> true);
            noReadFilterList.setPredicate(s-> true);
        } else {
            if (selectReadBtn.isSelected()) {
                readFilterList.setPredicate(s -> {
                    ImUser imUser = ImCacheFactory.getInstance().getUser(s.getUserId());
                    return imUser.getUserName().contains(filter);
                });
            }

            if (selectNoReadBtn.isSelected()) {
                noReadFilterList.setPredicate(s -> {
                    ImUser imUser = ImCacheFactory.getInstance().getUser(s.getUserId());
                    return imUser.getUserName().contains(filter);
                });
            }
        }
    }

    private ContextMenu createContextMenu(ImUser imUser) {
        ContextMenu contextMenu = new ContextMenu();
        MenuItem sendMessage = new MenuItem("发送消息");

        sendMessage.setOnAction((event) -> {
            UiUtil.getMainController().switchUserMessage(imUser, null);
        });
        contextMenu.getItems().add(sendMessage);
        return contextMenu;
    }

    private int messageSendComparator(ImMessageSend messageSend, ImMessageSend messageSend1) {
        return messageSend1.getUpdateTime().compareTo(messageSend.getUpdateTime());
    }
}
